package ru.spbau.bytecode.gui;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JPanel;

import ru.spbau.bytecode.graph.Graph;


public class GraphViewer extends JPanel {

	private Graph graph;

	public GraphViewer() {
		VertexHandler mouseListener = new VertexHandler();
		addMouseListener(mouseListener);
		addMouseMotionListener(mouseListener);
	}

	public void setGraph(Graph graph) {
		this.graph = graph;
		setPreferredSize(graph.calculateGraphSize());
		setSize(getPreferredSize());
		repaint();
	}

	@Override
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (graph != null) {
			graph.draw(g);
		}
	}
	
	
	private class VertexHandler extends MouseAdapter {
		
		private Point mousePosition;
		
		@Override
		public void mouseDragged(MouseEvent e) {
			if (graph != null) {
				graph.moveCatchedVertices(e.getPoint().x - mousePosition.x,
										e.getPoint().y - mousePosition.y);
				mousePosition = e.getPoint();
				GraphViewer.this.repaint();
			}
		}

		@Override
		public void mousePressed(MouseEvent e) {
			if (graph != null) {
				graph.catchVertexAtPoint(e.getPoint());
				mousePosition = e.getPoint();
			}
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			if (graph != null) {
				graph.freeCatchedVertices();
				Dimension size = graph.calculateGraphSize();
				GraphViewer.this.setPreferredSize(size);
				GraphViewer.this.setSize(size);
				GraphViewer.this.repaint();
			}
		}

	}
}
